package com.course.redisson.service;

import com.course.model.dto.UserDto;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @PROJECT_NAME: course
 * @DESCRIPTION: 由于Redisson的基于发布-订阅式的主题不具备“自动”监听的功能
 *               故需让消费者继承Spring提供的ApplicationRunner和Ordered接口
 * @Author: 涂玄武
 * @DATE: 2021/5/31 15:23
 */
@Component
public class UserLoginSubscriber implements ApplicationRunner, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(UserLoginSubscriber.class);

    //构造基于发布-订阅式主题的Key
    private static final String topicKey = "redisson:userLogin:topicKey";

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private SysLogService sysLogService;

    /**
     * 在这个方法里实现“不断监听该主题中消息的动态”，即间接地实现自动监听消费
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            RTopic topic = redissonClient.getTopic(topicKey);
            topic.addListener(UserDto.class, (charSequence, userDto) -> {
                logger.info("记录用户登录成功后的轨迹-消费者-监听消费到消息：{}",userDto);
                if (Objects.nonNull(userDto)){
                    sysLogService.recordLog(userDto);
                }
            });
        } catch (Exception e) {
            logger.error("记录用户登录成功后的轨迹-消费者-监听消费到消息-发生异常：",e.fillInStackTrace());
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
